<template>
  <div>
    <!-- 面包屑 -->
    <div class="mb-6 text-sm text-gray-500 flex items-center">
      <router-link to="/dashboard" class="hover:text-gray-700">控制台</router-link>
      <i class="fas fa-chevron-right mx-2"></i>
      <span class="text-gray-900 font-medium">巡检管理（新）</span>
    </div>

    <!-- 标题与操作 -->
    <div class="flex items-center justify-between mb-6">
      <div>
        <h1 class="text-2xl font-bold text-gray-900">巡检管理（新）</h1>
        <p class="text-gray-600 mt-1">计划与任务联动管理，支持看板视图</p>
      </div>
      <div class="flex space-x-3">
        <button 
          @click="handleAddPlan"
          class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors flex items-center space-x-2"
        >
          <i class="fas fa-plus"></i>
          <span>新增计划</span>
        </button>
        <button 
          v-if="selectedTasks.length > 0"
          @click="handleBatchAssign"
          class="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 transition-colors flex items-center space-x-2"
        >
          <i class="fas fa-share"></i>
          <span>批量分配 ({{ selectedTasks.length }})</span>
        </button>
        <button 
          @click="handleExport"
          class="bg-gray-600 text-white px-4 py-2 rounded-lg hover:bg-gray-700 transition-colors flex items-center space-x-2"
        >
          <i class="fas fa-file-export"></i>
          <span>导出数据</span>
        </button>
      </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
      <!-- 左：计划列表 -->
      <div class="lg:col-span-1">
        <div class="bg-white rounded-lg shadow-sm border border-gray-200">
          <div class="p-4 border-b">
            <div class="flex items-center justify-between">
              <h3 class="text-lg font-semibold">巡检计划</h3>
              <div class="text-sm text-gray-500">共 {{ planList.length }} 个</div>
            </div>
          </div>
          <div class="divide-y">
            <div 
              v-for="plan in planList" 
              :key="plan.id"
              @click="handlePlanSelect(plan)"
              :class="[
                'p-4 hover:bg-gray-50 cursor-pointer border-l-4',
                selectedPlan?.id === plan.id 
                  ? 'border-blue-500 bg-blue-50' 
                  : 'border-transparent'
              ]"
            >
              <div class="flex items-start justify-between">
                <div>
                  <h4 class="font-medium text-gray-800">{{ plan.name }}</h4>
                  <p class="text-xs text-gray-500 mt-1">周期：{{ cycleText[plan.cycle] }} / 负责人：{{ plan.assignee }}</p>
                </div>
                <span :class="getStatusClass(plan.status)" class="text-xs px-2 py-1 rounded-full">
                  {{ statusText[plan.status] }}
                </span>
              </div>
            </div>
            <div v-if="planList.length === 0" class="p-8 text-center text-gray-500">
              <i class="fas fa-inbox text-2xl mb-2"></i>
              <p>暂无计划</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 右：任务列表 -->
      <div class="lg:col-span-2">
        <div class="bg-white rounded-lg shadow-sm border border-gray-200">
          <div class="p-4 border-b flex items-center justify-between">
            <div class="flex items-center gap-3">
              <button 
                @click="viewMode = 'list'"
                :class="[
                  'px-3 py-2 rounded text-sm',
                  viewMode === 'list' ? 'bg-blue-600 text-white' : 'border border-gray-300 bg-white'
                ]"
              >
                任务列表
              </button>
              <button 
                @click="viewMode = 'kanban'"
                :class="[
                  'px-3 py-2 rounded text-sm',
                  viewMode === 'kanban' ? 'bg-blue-600 text-white' : 'border border-gray-300 bg-white'
                ]"
              >
                任务看板
              </button>
            </div>
            <div class="flex items-center gap-3">
              <div class="relative">
                <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
                <input 
                  v-model="taskSearchForm.keyword"
                  placeholder="搜索任务" 
                  class="pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  @keyup.enter="handleTaskSearch"
                />
              </div>
              <select 
                v-model="taskSearchForm.status"
                class="px-3 py-2 border border-gray-300 rounded-lg"
                @change="handleTaskSearch"
              >
                <option value="">全部状态</option>
                <option v-for="option in statusOptions" :key="option.value" :value="option.value">
                  {{ option.label }}
                </option>
              </select>
            </div>
          </div>
          
          <!-- 任务列表视图 -->
          <div v-if="viewMode === 'list'" class="overflow-x-auto">
            <table class="w-full">
              <thead class="bg-gray-50">
                <tr>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    <input 
                      type="checkbox" 
                      class="rounded border-gray-300"
                      :checked="selectAll"
                      @change="handleSelectAll($event.target.checked)"
                    />
                  </th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">任务编号</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">计划</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">人员</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">截止</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                </tr>
              </thead>
              <tbody class="bg-white divide-y divide-gray-200">
                <tr v-for="task in filteredTasks" :key="task.id" class="hover:bg-gray-50">
                  <td class="px-6 py-4">
                    <input 
                      type="checkbox" 
                      class="rounded border-gray-300"
                      :checked="selectedTasks.includes(task.id)"
                      @change="handleSelect($event.target.checked, task)"
                    />
                  </td>
                  <td class="px-6 py-4 text-sm font-medium text-gray-900">{{ task.code }}</td>
                  <td class="px-6 py-4 text-sm text-gray-500">{{ task.planName }}</td>
                  <td class="px-6 py-4 text-sm text-gray-500">{{ task.assignee }}</td>
                  <td class="px-6 py-4">
                    <span :class="getStatusClass(task.status)" class="inline-flex px-2 py-1 text-xs font-semibold rounded-full">
                      {{ statusText[task.status] }}
                    </span>
                  </td>
                  <td class="px-6 py-4 text-sm text-gray-500">{{ task.deadline }}</td>
                  <td class="px-6 py-4 text-sm">
                    <div class="flex items-center gap-2">
                      <button 
                        @click="handleViewTask(task)"
                        class="text-blue-600 hover:text-blue-800"
                        title="查看详情"
                      >
                        <i class="fas fa-eye"></i>
                      </button>
                      <button 
                        @click="handleEditTask(task)"
                        class="text-green-600 hover:text-green-800"
                        title="编辑"
                      >
                        <i class="fas fa-edit"></i>
                      </button>
                      <button 
                        @click="handleAssignTask(task)"
                        class="text-purple-600 hover:text-purple-800"
                        title="分配任务"
                      >
                        <i class="fas fa-user-plus"></i>
                      </button>
                      <button 
                        @click="handleDeleteTask(task)"
                        class="text-red-600 hover:text-red-800"
                        title="删除"
                      >
                        <i class="fas fa-trash"></i>
                      </button>
                    </div>
                  </td>
                </tr>
                <tr v-if="filteredTasks.length === 0">
                  <td colspan="7" class="px-6 py-8 text-center text-gray-500">
                    <i class="fas fa-inbox text-4xl mb-2"></i>
                    <p>暂无任务</p>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
          
          <!-- 任务看板视图 -->
          <div v-else class="p-6">
            <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
              <div v-for="status in kanbanStatuses" :key="status.value" class="bg-gray-50 rounded-lg p-4">
                <h4 class="font-medium text-gray-800 mb-3">{{ status.label }}</h4>
                <div class="space-y-3">
                  <div 
                    v-for="task in getTasksByStatus(status.value)" 
                    :key="task.id"
                    class="bg-white rounded-lg p-3 shadow-sm border border-gray-200 cursor-pointer hover:shadow-md transition-shadow"
                    @click="handleViewTask(task)"
                  >
                    <div class="flex items-start justify-between mb-2">
                      <h5 class="font-medium text-sm text-gray-900">{{ task.name }}</h5>
                      <span :class="getStatusClass(task.status)" class="text-xs px-2 py-1 rounded-full">
                        {{ statusText[task.status] }}
                      </span>
                    </div>
                    <p class="text-xs text-gray-500 mb-2">{{ task.assignee }}</p>
                    <p class="text-xs text-gray-400">{{ task.deadline }}</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <div class="px-6 py-3 border-t border-gray-200 flex items-center justify-between">
            <div class="text-sm text-gray-500">显示 1-{{ filteredTasks.length }} 条，共 {{ filteredTasks.length }} 条</div>
            <div class="flex items-center gap-2">
              <button 
                @click="handleRefresh"
                class="text-blue-600 hover:text-blue-800 flex items-center space-x-1"
              >
                <i class="fas fa-sync-alt"></i>
                <span>刷新</span>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 新增/编辑/查看计划弹窗 -->
    <div v-if="dialogVisible" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg shadow-xl w-full max-w-2xl mx-4 max-h-[90vh] overflow-y-auto">
        <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
          <h3 class="text-lg font-semibold text-gray-900">{{ dialogTitle }}</h3>
          <button 
            @click="dialogVisible = false"
            class="text-gray-400 hover:text-gray-600"
          >
            <i class="fas fa-times text-xl"></i>
          </button>
        </div>
        
        <div class="p-6">
          <form @submit.prevent="handleSave" class="space-y-4">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">计划名称 *</label>
                <input 
                  v-model="formData.name"
                  type="text"
                  :disabled="dialogMode === 'view'"
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  placeholder="请输入计划名称"
                >
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">巡检路线 *</label>
                <select 
                  v-model="formData.lineId"
                  :disabled="dialogMode === 'view'"
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                >
                  <option value="">请选择巡检路线</option>
                  <option v-for="line in lineOptions" :key="line.id" :value="line.id">
                    {{ line.name }}
                  </option>
                </select>
              </div>
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">负责人 *</label>
                <select 
                  v-model="formData.assigneeId"
                  :disabled="dialogMode === 'view'"
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                >
                  <option value="">请选择负责人</option>
                  <option v-for="user in userOptions" :key="user.id" :value="user.id">
                    {{ user.name }}
                  </option>
                </select>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">巡检周期 *</label>
                <select 
                  v-model="formData.cycle"
                  :disabled="dialogMode === 'view'"
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                >
                  <option value="">请选择巡检周期</option>
                  <option v-for="option in cycleOptions" :key="option.value" :value="option.value">
                    {{ option.label }}
                  </option>
                </select>
              </div>
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">状态</label>
                <select 
                  v-model="formData.status"
                  :disabled="dialogMode === 'view'"
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                >
                  <option v-for="option in planStatusOptions" :key="option.value" :value="option.value">
                    {{ option.label }}
                  </option>
                </select>
              </div>
              <div v-if="dialogMode === 'view'">
                <label class="block text-sm font-medium text-gray-700 mb-1">创建时间</label>
                <input 
                  v-model="formData.createTime"
                  type="text"
                  disabled
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg bg-gray-50"
                >
              </div>
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">描述</label>
              <textarea 
                v-model="formData.description"
                :disabled="dialogMode === 'view'"
                rows="3"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                placeholder="请输入计划描述"
              ></textarea>
            </div>
          </form>
        </div>
        
        <div class="px-6 py-4 border-t border-gray-200 flex justify-end space-x-3">
          <button 
            @click="dialogVisible = false"
            class="px-4 py-2 text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 transition-colors"
          >
            取消
          </button>
          <button 
            v-if="dialogMode !== 'view'"
            @click="handleSave"
            class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            {{ dialogMode === 'add' ? '新增' : '保存' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 任务分配弹窗 -->
    <div v-if="assignDialogVisible" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg shadow-xl w-full max-w-md mx-4">
        <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
          <h3 class="text-lg font-semibold text-gray-900">分配任务</h3>
          <button 
            @click="assignDialogVisible = false"
            class="text-gray-400 hover:text-gray-600"
          >
            <i class="fas fa-times text-xl"></i>
          </button>
        </div>
        
        <div class="p-6">
          <div class="space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">任务信息</label>
              <div class="p-3 bg-gray-50 rounded-lg">
                <p class="text-sm font-medium">{{ assignForm.taskName }}</p>
                <p class="text-xs text-gray-500">{{ assignForm.lineName }}</p>
              </div>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">分配给 *</label>
              <select 
                v-model="assignForm.assigneeId"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              >
                <option value="">请选择负责人</option>
                <option v-for="user in userOptions" :key="user.id" :value="user.id">
                  {{ user.name }}
                </option>
              </select>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">截止时间 *</label>
              <input 
                v-model="assignForm.deadline"
                type="datetime-local"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              >
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">备注</label>
              <textarea 
                v-model="assignForm.remark"
                rows="3"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                placeholder="请输入分配备注"
              ></textarea>
            </div>
          </div>
        </div>
        
        <div class="px-6 py-4 border-t border-gray-200 flex justify-end space-x-3">
          <button 
            @click="assignDialogVisible = false"
            class="px-4 py-2 text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 transition-colors"
          >
            取消
          </button>
          <button 
            @click="handleAssignSave"
            class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            分配
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { inspectionAPI } from '@/api/modules'

/**
 * 响应式数据
 */
// 计划列表
const planList = ref([])
const selectedPlan = ref(null)

// 任务列表
const taskList = ref([])
const viewMode = ref('list') // list, kanban

// 任务搜索表单
const taskSearchForm = ref({
  keyword: '',
  status: ''
})

// 选中的任务
const selectedTasks = ref([])
const selectAll = ref(false)

// 弹窗状态
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogMode = ref('add') // add, edit, view

// 分配弹窗状态
const assignDialogVisible = ref(false)

// 表单数据
const formData = ref({
  id: null,
  name: '',
  lineId: '',
  assigneeId: '',
  cycle: '',
  status: 'active',
  description: '',
  createTime: ''
})

// 分配表单数据
const assignForm = ref({
  taskId: null,
  taskName: '',
  lineName: '',
  assigneeId: '',
  deadline: '',
  remark: ''
})

// 选项数据
// 巡检计划状态选项（只有启用和禁用）
const planStatusOptions = [
  { label: '启用', value: 'active' },
  { label: '禁用', value: 'disabled' }
]

// 巡检任务状态选项
const taskStatusOptions = [
  { label: '待分配', value: 'pending' },
  { label: '进行中', value: 'in_progress' },
  { label: '待回执', value: 'pending_receipt' },
  { label: '已完成', value: 'completed' },
  { label: '超时', value: 'timeout' },
  { label: '已停用', value: 'disabled' }
]

const cycleOptions = [
  { label: '日', value: 'daily' },
  { label: '周', value: 'weekly' },
  { label: '月', value: 'monthly' },
  { label: '自定义', value: 'custom' }
]

const lineOptions = ref([
  { id: 1, name: '东区主干管道' },
  { id: 2, name: '西区支线管道' },
  { id: 3, name: '南区连接管道' },
  { id: 4, name: '北区备用管道' }
])

const userOptions = ref([
  { id: 1, name: '王强' },
  { id: 2, name: '李雷' },
  { id: 3, name: '张明' },
  { id: 4, name: '刘华' }
])

// 看板状态
const kanbanStatuses = [
  { label: '待分配', value: 'pending' },
  { label: '进行中', value: 'in_progress' },
  { label: '待回执', value: 'pending_receipt' },
  { label: '已完成', value: 'completed' }
]

/**
 * 计算属性
 */
// 计划状态文本映射
const planStatusText = computed(() => {
  const statusMap = {
    active: '启用',
    disabled: '禁用'
  }
  return statusMap
})

// 任务状态文本映射
const taskStatusText = computed(() => {
  const statusMap = {
    pending: '待分配',
    in_progress: '进行中',
    pending_receipt: '待回执',
    completed: '已完成',
    timeout: '超时',
    disabled: '已停用'
  }
  return statusMap
})

// 通用状态文本映射（兼容旧代码）
const statusText = computed(() => {
  return { ...planStatusText.value, ...taskStatusText.value }
})

const cycleText = computed(() => {
  const cycleMap = {
    daily: '日',
    weekly: '周',
    monthly: '月',
    custom: '自定义'
  }
  return cycleMap
})

const filteredTasks = computed(() => {
  let filtered = [...taskList.value]
  
  // 如果选择了计划，只显示该计划的任务
  if (selectedPlan.value) {
    filtered = filtered.filter(task => task.planId === selectedPlan.value.id)
  }
  
  // 关键词搜索
  if (taskSearchForm.value.keyword) {
    filtered = filtered.filter(task => 
      task.code.toLowerCase().includes(taskSearchForm.value.keyword.toLowerCase()) ||
      task.name.toLowerCase().includes(taskSearchForm.value.keyword.toLowerCase())
    )
  }
  
  // 状态筛选
  if (taskSearchForm.value.status) {
    filtered = filtered.filter(task => task.status === taskSearchForm.value.status)
  }
  
  return filtered
})

/**
 * 模拟数据
 */
const mockPlanData = [
  {
    id: 1,
    code: 'P-2025-001',
    name: '东区周检计划',
    lineId: 1,
    lineName: '东区主干管道',
    assigneeId: 1,
    assignee: '王强',
    cycle: 'weekly',
    status: 'active',
    description: '东区每周定期巡检计划',
    createTime: '2025-01-01 10:00:00'
  },
  {
    id: 2,
    code: 'P-2025-002',
    name: '东区月度巡检',
    lineId: 1,
    lineName: '东区主干管道',
    assigneeId: 2,
    assignee: '李雷',
    cycle: 'monthly',
    status: 'disabled',
    description: '东区每月定期巡检计划',
    createTime: '2025-01-02 14:30:00'
  },
  {
    id: 3,
    code: 'P-2025-003',
    name: '西区日检计划',
    lineId: 2,
    lineName: '西区支线管道',
    assigneeId: 3,
    assignee: '张明',
    cycle: 'daily',
    status: 'active',
    description: '西区每日巡检计划',
    createTime: '2025-01-03 09:15:00'
  }
]

const mockTaskData = [
  {
    id: 1,
    code: 'T-2025-001',
    name: '东区周检计划',
    planId: 1,
    planName: '东区周检计划',
    lineId: 1,
    lineName: '东区主干管道',
    assigneeId: 1,
    assignee: '王强',
    cycle: 'weekly',
    status: 'in_progress',
    deadline: '2025-01-31 18:00',
    createTime: '2025-01-15 09:00:00'
  },
  {
    id: 2,
    code: 'T-2025-002',
    name: '东区月度巡检',
    planId: 2,
    planName: '东区月度巡检',
    lineId: 1,
    lineName: '东区主干管道',
    assigneeId: 2,
    assignee: '李雷',
    cycle: 'monthly',
    status: 'pending',
    deadline: '2025-02-28 18:00',
    createTime: '2025-01-20 10:30:00'
  },
  {
    id: 3,
    code: 'T-2025-003',
    name: '西区日检计划',
    planId: 3,
    planName: '西区日检计划',
    lineId: 2,
    lineName: '西区支线管道',
    assigneeId: 3,
    assignee: '张明',
    cycle: 'daily',
    status: 'completed',
    deadline: '2025-01-25 18:00',
    createTime: '2025-01-25 08:00:00'
  },
  {
    id: 4,
    code: 'T-2025-004',
    name: '南区连接管道巡检',
    planId: null,
    planName: '独立任务',
    lineId: 3,
    lineName: '南区连接管道',
    assigneeId: 4,
    assignee: '刘华',
    cycle: 'custom',
    status: 'timeout',
    deadline: '2025-01-20 18:00',
    createTime: '2025-01-18 14:00:00'
  },
  {
    id: 5,
    code: 'T-2025-005',
    name: '东区周检计划-2',
    planId: 1,
    planName: '东区周检计划',
    lineId: 1,
    lineName: '东区主干管道',
    assigneeId: 1,
    assignee: '王强',
    cycle: 'weekly',
    status: 'pending_receipt',
    deadline: '2025-02-07 18:00',
    createTime: '2025-02-01 09:00:00'
  }
]

/**
 * 获取计划列表
 */
const loadPlanList = async () => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 300))
    planList.value = [...mockPlanData]
  } catch (error) {
    console.error('加载计划列表失败:', error)
    ElMessage.error('加载计划列表失败')
  }
}

/**
 * 获取任务列表
 */
const loadTaskList = async () => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 300))
    taskList.value = [...mockTaskData]
  } catch (error) {
    console.error('加载任务列表失败:', error)
    ElMessage.error('加载任务列表失败')
  }
}

/**
 * 选择计划
 */
const handlePlanSelect = (plan) => {
  selectedPlan.value = plan
  selectedTasks.value = []
  selectAll.value = false
}

/**
 * 任务搜索
 */
const handleTaskSearch = () => {
  selectedTasks.value = []
  selectAll.value = false
}

/**
 * 全选/取消全选
 */
const handleSelectAll = (checked) => {
  selectAll.value = checked
  if (checked) {
    selectedTasks.value = filteredTasks.value.map(task => task.id)
  } else {
    selectedTasks.value = []
  }
}

/**
 * 单个选择
 */
const handleSelect = (checked, task) => {
  if (checked) {
    selectedTasks.value.push(task.id)
  } else {
    const index = selectedTasks.value.indexOf(task.id)
    if (index > -1) {
      selectedTasks.value.splice(index, 1)
    }
  }
  
  // 更新全选状态
  selectAll.value = selectedTasks.value.length === filteredTasks.value.length
}

/**
 * 新增计划
 */
const handleAddPlan = () => {
  dialogMode.value = 'add'
  dialogTitle.value = '新增计划'
  formData.value = {
    id: null,
    name: '',
    lineId: '',
    assigneeId: '',
    cycle: '',
    status: 'active',
    description: '',
    createTime: ''
  }
  dialogVisible.value = true
}

/**
 * 查看任务
 */
const handleViewTask = (task) => {
  dialogMode.value = 'view'
  dialogTitle.value = '任务详情'
  formData.value = { ...task }
  dialogVisible.value = true
}

/**
 * 编辑任务
 */
const handleEditTask = (task) => {
  dialogMode.value = 'edit'
  dialogTitle.value = '编辑任务'
  formData.value = { ...task }
  dialogVisible.value = true
}

/**
 * 分配任务
 */
const handleAssignTask = (task) => {
  assignForm.value = {
    taskId: task.id,
    taskName: task.name,
    lineName: task.lineName,
    assigneeId: '',
    deadline: '',
    remark: ''
  }
  assignDialogVisible.value = true
}

/**
 * 删除任务
 */
const handleDeleteTask = async (task) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除任务"${task.name}"吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟删除API调用
    await new Promise(resolve => setTimeout(resolve, 300))
    
    ElMessage.success('删除成功')
    loadTaskList()
    
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

/**
 * 批量分配
 */
const handleBatchAssign = () => {
  if (selectedTasks.value.length === 0) {
    ElMessage.warning('请选择要分配的任务')
    return
  }
  
  ElMessage.info('批量分配功能开发中...')
}

/**
 * 保存
 */
const handleSave = async () => {
  try {
    // 表单验证
    if (!formData.value.name.trim()) {
      ElMessage.warning('请输入计划名称')
      return
    }
    if (!formData.value.lineId) {
      ElMessage.warning('请选择巡检路线')
      return
    }
    if (!formData.value.assigneeId) {
      ElMessage.warning('请选择负责人')
      return
    }
    if (!formData.value.cycle) {
      ElMessage.warning('请选择巡检周期')
      return
    }
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    if (dialogMode.value === 'add') {
      ElMessage.success('新增计划成功')
    } else {
      ElMessage.success('编辑成功')
    }
    
    dialogVisible.value = false
    loadPlanList()
    
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

/**
 * 保存分配
 */
const handleAssignSave = async () => {
  try {
    // 表单验证
    if (!assignForm.value.assigneeId) {
      ElMessage.warning('请选择负责人')
      return
    }
    if (!assignForm.value.deadline) {
      ElMessage.warning('请选择截止时间')
      return
    }
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success('任务分配成功')
    assignDialogVisible.value = false
    loadTaskList()
    
  } catch (error) {
    ElMessage.error('分配失败')
  }
}

/**
 * 导出数据
 */
const handleExport = async () => {
  try {
    ElMessage.info('正在导出数据...')
    
    // 模拟导出API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('导出成功')
    
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

/**
 * 刷新数据
 */
const handleRefresh = () => {
  loadPlanList()
  loadTaskList()
}

/**
 * 获取状态样式类
 */
const getStatusClass = (status) => {
  const classes = {
    // 计划状态样式
    active: 'bg-green-100 text-green-800',
    disabled: 'bg-gray-100 text-gray-800',
    // 任务状态样式
    pending: 'bg-yellow-100 text-yellow-800',
    in_progress: 'bg-blue-100 text-blue-800',
    pending_receipt: 'bg-orange-100 text-orange-800',
    completed: 'bg-green-100 text-green-800',
    timeout: 'bg-red-100 text-red-800'
  }
  return classes[status] || 'bg-gray-100 text-gray-800'
}

/**
 * 根据状态获取任务
 */
const getTasksByStatus = (status) => {
  return filteredTasks.value.filter(task => task.status === status)
}

/**
 * 组件挂载时加载数据
 */
onMounted(() => {
  loadPlanList()
  loadTaskList()
})
</script>
